<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="$t('上传升级文件')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="550px" top="5%" @close='close'>
    <el-upload class="upload-Upgrade" ref="upload" :action="global + '/update/upload'" accept='.firmware' :on-change="handleChange" :headers='headerConfig' :multiple='false' :file-list="fileList" :auto-upload="false">
      <el-button slot="trigger" size="small" type="primary">{{$t('选取文件')}}</el-button>
    </el-upload>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>

import global from '@/global'
import { getSessionId } from '@/utils/auth'
import { updateCheck } from '@/api/system/update'
export default {
  name: 'uploadFile',
  data () {
    return {
      dialogVisible: false,
      fileList: [],
      headerConfig: {
        'session_id': getSessionId()
      },
      global: global.BASE_URL
    }
  },
  methods: {
    init () {
      this.dialogVisible = true
    },
    async submit () {
      await this.$refs.upload.submit()
      await updateCheck({ name: this.fileList[0].name }).then(res => {
        if (res.status === 0) {
          this.$messages.success(this.$t('上传成功'))
          this.$parent.listData()
          this.close()
        } else {
          this.$refs.upload.clearFiles()
          this.$messages.error(this.$t('上传失败，请重新上传'))
        }
      })
    },
    // submit () {
    //   this.$refs.upload.submit()
    //   this.$parent.listData()
    //   this.close()
    // },
    handleChange (file, fileList) {
      const isFirmware = file.name.indexOf('.firmware') >= 0
      if (!isFirmware) {
        this.$messages.error(this.$t('上传的文件只能是 firmware 格式!'))
        fileList.splice(-1, 1)
        this.fileList = fileList
      } else if (fileList.length > 1) {
        fileList.splice(0, 1)
        this.fileList = fileList
      } else {
        this.fileList = fileList
      }
      return isFirmware
    },
    close () {
      this.$refs.upload.clearFiles()
      this.dialogVisible = false
    }
  }
}
</script>
